package cn.bonoon.kernel.util;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;


/**
 * 字符串处理的辅助对象
 * 
 * @author jackson
 * 
 */
public final class StringHelper {
	public final static String Empty = "";
	public final static String NULL = null;

	public final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	public final static String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public final static String DEFAULT_TIME_FORMAT = "HH:mm:ss";

	public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
	public static SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
	public static SimpleDateFormat simpleTimeFormat = new SimpleDateFormat(DEFAULT_TIME_FORMAT);


	/**
	 * 获取非空字符串，否则抛出异常，null、空串和纯空格都算空
	 */
	public static String getNotEmptyString(String value, String msg) throws Exception{
		if(null==value || "".equals(value.trim())){
			throw new Exception(msg);
		}
		return value;
	}
	
	/**
	 * 判断指定的字符串是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return null == str || str.isEmpty();
	}

	/** 判断指定的字符串是否不为空 */
	public static boolean isNotEmpty(String str) {
		return null != str && !str.isEmpty();
	}
	
	public static String date2String(Date date) {
		return __toString(date, simpleDateFormat);
	}

	public static String date2String(long date) {
		return __toString(new Date(date), simpleDateFormat);
	}

	/** 有时分秒 */
	public static String datetime2String(Date date) {
		return __toString(date, simpleDateTimeFormat);
	}
	
	public static String time2String(Date date) {
		return __toString(date, simpleTimeFormat);
	}
	
	private static String __toString(Date date, SimpleDateFormat sdf){
		return null == date ? NULL : sdf.format(date);
	}
	
	private static Date __toDate(String str, SimpleDateFormat sdf){
		try {
			if (isNotEmpty(str)) return sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date toDate(String str) {
		return __toDate(str, simpleDateFormat);
	}

	/**
	 * 
	 * 有时分秒
	 * 
	 * @param str
	 * @return
	 */
	public static Date toDatetime(String str) {
		try {
			if (isNotEmpty(str)){
				boolean d = str.indexOf('-') > 0, t = str.indexOf(':') > 0;
				if(d && t){
					return simpleDateTimeFormat.parse(str);
				}else if(d){
					return simpleDateFormat.parse(str);
				}else if(t){
					return simpleTimeFormat.parse(str);
				}
			}
		} catch (ParseException e) {
		}
		return null;
	}

	public static Boolean contains(String[] a, int fromIndex, int toIndex, String key) {
		rangeCheck(a.length, fromIndex, toIndex);
		return __indexOf(a, fromIndex, toIndex, key) >= fromIndex;
	}

	private static int __indexOf(String[] a, int fromIndex, int toIndex, String key) {
		int low = fromIndex;
		int high = toIndex - 1;

		while (low <= high) {
			int mid = (low + high) >>> 1;
			String midVal = a[mid];
			int cmp = midVal.compareTo(key);

			if (cmp < 0)
				low = mid + 1;
			else if (cmp > 0)
				high = mid - 1;
			else
				return mid; // key found
		}
		return -(low + 1); // key not found.
	}

	public static Boolean contains(String[] a, String key) {
		return __indexOf(a, 0, a.length, key) != -1;
	}

	/**
	 * Check that fromIndex and toIndex are in range, and throw an appropriate
	 * exception if they aren't.
	 */
	private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
		if (fromIndex > toIndex)
			throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
		if (fromIndex < 0)
			throw new ArrayIndexOutOfBoundsException(fromIndex);
		if (toIndex > arrayLen)
			throw new ArrayIndexOutOfBoundsException(toIndex);
	}

	public static String delimiter(String pattern) {
		return null == pattern || pattern.isEmpty() ? "," : pattern;
	}
	
	public static Long[] toLongArray(String data) {
		return toLongArray(data, null);
	}

	public static Long[] toLongArray(String data, String pattern) {
		if (isEmpty(data))
			return null;
		String delimiter = delimiter(pattern);
		String[] idStrings = data.split(delimiter);
		Long[] idsLongs = new Long[idStrings.length];
		for (int i = 0; i < idStrings.length; i++)
			idsLongs[i] = Long.parseLong(idStrings[i], 10);
		return idsLongs;
	}
	
	public static Double[] toDoubleArray(String data) {
		return toDoubleArray(data, null);
	}

	public static Double[] toDoubleArray(String data, String pattern) {
		if (isEmpty(data))
			return null;
		String delimiter = delimiter(pattern);
		String[] idStrings = data.split(delimiter);
		Double[] idsDoubles = new Double[idStrings.length];
		for (int i = 0; i < idStrings.length; i++)
			idsDoubles[i] = Double.parseDouble(idStrings[i]);
		return idsDoubles;
	}
	
	public static int[] toIntegerArray(String data) {
		return toIntegerArray(data, null);
	}

	public static int[] toIntegerArray(String data, String pattern) {
		if (isEmpty(data))
			return null;
		String delimiter = delimiter(pattern);
		String[] idStrings = data.split(delimiter);
		int[] idsLongs = new int[idStrings.length];
		for (int i = 0; i < idStrings.length; i++)
			idsLongs[i] = Integer.parseInt(idStrings[i], 10);
		return idsLongs;
	}


	public static boolean toboolean(String data) {
		if (isEmpty(data))
			return false;
		try {
			return ((data != null) && data.equalsIgnoreCase("true"));
		} catch (Throwable e) {
			return false;
		}
	}

	public static Boolean toBoolean(String data) {
		if (isEmpty(data))
			return null;
		try {
			return ((data != null) && data.equalsIgnoreCase("true"));
		} catch (Throwable e) {
			return null;
		}
	}

	public static boolean toboolean(String data, boolean defaultValue) {
		if (isEmpty(data))
			return defaultValue;
		try {
			return ((data != null) && data.equalsIgnoreCase("true"));
		} catch (Throwable e) {
			return defaultValue;
		}
	}

	public static Character toChar(String data) {
		if (isEmpty(data))
			return null;
		return data.charAt(0);
	}

	public static char tochar(String data) {
		if (isEmpty(data))
			return 0;
		return data.charAt(0);
	}

	public static Byte toByte(String data) {
		if (isEmpty(data))
			return null;
		return data.getBytes()[0];
	}

	public static byte tobyte(String data) {
		if (isEmpty(data))
			return 0;
		return data.getBytes()[0];
	}

	public static Short toShort(String data) {
		if (isEmpty(data))
			return null;
		try {
			return Short.parseShort(data, 10);
		} catch (Throwable e) {
			return null;
		}
	}

	public static short toshort(String data) {
		if (isEmpty(data))
			return 0;
		try {
			return Short.parseShort(data, 10);
		} catch (Throwable e) {
			return 0;
		}
	}

	public static Long toLong(String data) {
		if (isEmpty(data))
			return null;
		try {
			return Long.parseLong(data, 10);
		} catch (Throwable e) {
			return null;
		}
	}

	public static long tolong(String data) {
		if (isEmpty(data))
			return 0;
		try {
			return Long.parseLong(data, 10);
		} catch (Throwable e) {
			return 0;
		}
	}

	public static long tolong(String data, long defaultValue) {
		if (isEmpty(data))
			return defaultValue;
		try {
			return Long.parseLong(data, 10);
		} catch (Throwable e) {
			return defaultValue;
		}
	}

	public static Integer toInteger(String data) {
		if (isEmpty(data))
			return null;
		try {
			return Integer.parseInt(data, 10);
		} catch (Throwable e) {
			return null;
		}
	}
	public static int toint(String data) {
		return toint(data, 0);
	}

	public static int toint(String data, int def) {
		if (isEmpty(data))
			return def;
		try {
			return Integer.parseInt(data, 10);
		} catch (Throwable e) {
			return def;
		}
	}

	public static Float toFloat(String data) {
		if (isEmpty(data))
			return null;
		try {
			return Float.parseFloat(data);
		} catch (Throwable e) {
			return null;
		}
	}

	public static float tofloat(String data) {
		if (isEmpty(data))
			return 0;
		try {
			return Float.parseFloat(data);
		} catch (Throwable e) {
			return 0;
		}
	}
	
	public static Double toDouble(String data) {
		if (isEmpty(data))
			return null;
		try {
			return Double.parseDouble(data);
		} catch (Throwable e) {
			return null;
		}
	}
	
	public static double todouble(String data) {
		if (isEmpty(data))
			return 0;
		try {
			return Double.parseDouble(data);
		} catch (Throwable e) {
			return 0;
		}
	}

	public static double todouble(String data, double defaultValue) {
		if (isEmpty(data))
			return defaultValue;
		try {
			return Double.parseDouble(data);
		} catch (Throwable e) {
			return defaultValue;
		}
	}

	public static int[] tointArray(String data) {
		if (isEmpty(data))
			return new int[0];
		try {
			List<String> list = toList(data);
			int[] is = new int[list.size()];
			int i = 0;
			for (String str : list) {
				is[i++] = Integer.parseInt(str, 10);
			}
			return is;
		} catch (Throwable e) {
			return new int[0];
		}
	}

	public static List<String> toList(String str) {
		return toList(new ArrayList<String>(), str, ',');
	}

	public static List<String> toList(List<String> list, String str) {
		return toList(list, str, ',');
	}

	public static List<String> toList(List<String> list, String str, char s) {
		if (isNotEmpty(str)) {
			String sub = null;
			int index = -1, offset = 0;
			char[] chs = str.toCharArray();
			while ((index = indexOf(chs, s, index + 1)) != -1) {
				if (index > offset) {
					sub = substring(chs, offset, index);
					if (!list.contains(sub))
						list.add(sub);
				}
				offset = index + 1;
			}
			if (offset > 0) {// 处理最后一个
				sub = substring(chs, offset);
				if (isNotEmpty(sub) && !list.contains(sub))
					list.add(sub);
			} else {
				// 只有一个
				list.add(str);
			}
		}
		return list;
	}

	public static List<DataItem> toData(String str) {
		List<DataItem> list = new ArrayList<DataItem>();
		if (isNotEmpty(str)) {
			String sub = null;
			int index = -1, offset = 0;
			char[] chs = str.toCharArray();
			while ((index = indexOf(chs, ',', index + 1)) != -1) {
				if (index > offset) {
					sub = substring(chs, offset, index);
					if (!list.contains(sub))
						list.add(new DataItem(sub));
				}
				offset = index + 1;
			}
			if (offset > 0) {// 处理最后一个
				sub = substring(chs, offset);
				if (isNotEmpty(sub) && !list.contains(sub))
					list.add(new DataItem(sub));
			} else {
				// 只有一个
				list.add(new DataItem(sub));
			}
		}
		return list;
	}
	
	public static class DataItem{
		DataItem(String value){
			this.text = value;
			this.value = value;
		}
		final String value;
		final String text;
		public String getValue(){
			return value;
		}
		public String getText(){
			return text;
		}
	}

	/**
	 * 去掉空值,去掉重复
	 */
	public static List<String> toList(String str, char s) {
		return toList(new ArrayList<String>(), str, s);
	}

	private static String substring(char[] chs, int beginIndex, int endIndex) {
		int count = endIndex - beginIndex;
		return count > 0 ? new String(chs, beginIndex, count) : null;
	}

	private static String substring(char[] chs, int beginIndex) {
		return substring(chs, beginIndex, chs.length);
	}

	private static int indexOf(char[] chs, char ch, int fromIndex) {
		for (int i = fromIndex; i < chs.length; i++) {
			if (chs[i] == ch) return i;
		}
		return -1;
	}

	public static String join(String seperator, Object... strings) {
		if (null == strings || strings.length == 0) return Empty;
		if(null == seperator) seperator = ",";
		StringBuffer buf = new StringBuffer();
		for(Object str : strings){
			buf.append(seperator).append(str);
		}
		return buf.substring(seperator.length());
	}

	public static String join(String seperator, Long... strings) {
		if (null == strings || strings.length == 0) return Empty;
		if(null == seperator) seperator = ",";
		StringBuffer buf = new StringBuffer();
		for(Long str : strings){
			buf.append(seperator).append(str);
		}
		if(buf.length() > 0){
			return buf.substring(seperator.length());
		}
		return "";
	}

	public static String join(String seperator, List<Object> strings) {
		if (null == strings || strings.isEmpty()) return Empty;
		if(null == seperator) seperator = ",";
		StringBuffer buf = new StringBuffer();
		for(Object str : strings){
			buf.append(seperator).append(str);
		}
		return buf.substring(seperator.length());
	}

//	public static String join(char seperator, String... strings) {
//		int length = strings.length;
//		if (length == 0) return Empty;
//		int newLen = 0;
//		for(int i = 0; i < length; i++){
//			String str = strings[i];
//			if(isNotEmpty(str)){
//				strings[newLen++] = str;
//			}
//		}
//		if(newLen == 0) return Empty;
//		StringBuffer buf = new StringBuffer(strings[0]);
//		for (int i = 1; i < newLen; i++) {
//			buf.append(seperator).append(strings[i]);
//		}
//		return buf.toString();
//	}

	public static String lastOfUri(String uri) {
		if (isNotEmpty(uri)) {
			char[] cs = uri.toCharArray();
			int p = cs.length;
			while (p > 0 && cs[--p] == '/');
			if (p > 0) {
				int s = p;
				while (s > 0 && cs[--s] != '/');
				if (s >= 0) {
					return uri.substring(s + 1, p + 1);
				}
			}
		}
		return uri;
	}

	public static String addQueryString(String url, String queryString) {
		return url + (url.indexOf("?", 0) == -1 ? '?' : '&') + queryString;
	}

	public static void main(String[] args) {
		String uri1 = "";
		String uri2 = "/df/ss/";
		String uri3 = "/";
		String uri4 = "/ddff/";
		String uri5 = "/sdffsd";

		System.out.println(lastOfUri(uri1));
		System.out.println(lastOfUri(uri2));
		System.out.println(lastOfUri(uri3));
		System.out.println(lastOfUri(uri4));
		System.out.println(lastOfUri(uri5));

		String s = ",aa,bb,cc,dd,ee,,,";
		List<String> ss = null;
		String[] sssss = null;
		long s1 = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
			ss = toList(s);
		}
		long s2 = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
			sssss = s.split(",");
		}
		long s3 = System.currentTimeMillis();

		System.out.println("tolist:" + (s2 - s1));
		System.out.println("split:" + (s3 - s2));

		System.out.println(ss.size());
		System.out.println(ss);
		System.out.println(sssss);
	}

	public static int lastIndexOf(String str, char c) {
		char[] chs = str.toCharArray();
		for (int i = chs.length - 1; i >= 0; i--) {
			if (chs[i] == c) return i;
		}
		return -1;
	}

	/**
	 * 两个数组中,只要有一个元素相同,则返回true
	 * 
	 * @param list1
	 * @param list2
	 * @return
	 */
	public static boolean anyContains(List<String> list1, List<String> list2) {
		if (null != list1 && null != list2) {
			for (String str : list1) {
				if (list2.contains(str))
					return true;
			}
		}
		return false;
	}

	public static List<String> emptyList() {
		return Collections.emptyList();
	}

	/**
	 * 
	 * @param rootDirPath
	 * @param path
	 *            必须不能为空并且有值
	 * @return
	 */
	public static String path(String root, String path) {
		StringBuilder sb = new StringBuilder();
		sb.append('/');
		char[] rs = null != root ? root.toCharArray() : new char[0];
		char[] ps = null != path ? path.toCharArray() : new char[0];
		char preChar, cc;
		if(rs.length > 0){
			preChar = rs[0];
			if(preChar != '/') sb.append(preChar);
			for(int i = 1; i < rs.length; i++){
				cc = rs[i];
				if(cc != '/' || cc != preChar) sb.append(cc);
				preChar = cc;
			}
			if(preChar != '/'){
				preChar = '/';
				sb.append(preChar);
			}
		}else{
			preChar = '/';
		}
		for(int i = 0; i < ps.length; i ++){
			cc = ps[i];
			if(cc != '/' || cc != preChar) sb.append(cc);
			preChar = cc;
		}
		return sb.toString();
	}

	public static String lastSubstring(String path, char c) {
		int i = lastIndexOf(path, c);
		return i == -1 ? null : path.substring(i);
	}

	public static String path(String path) {
		return path.charAt(0) == File.separatorChar ? path : File.separatorChar + path;
	}

	public static String path(HttpServletRequest request, String url) {
		return path(request.getRequestURI(), url);
	}

	public static String get(String arg1, String arg2) {
		return isNotEmpty(arg1) ? arg1 : arg2;
	}

	public static String get(String... args) {
		for(String arg : args){
			if(isNotEmpty(arg)) return arg;
		}
		return "";
	}

	public static String get(Object... args) {
		for(Object arg : args){
			if(null != arg){
				String str = arg.toString();
				if(!str.isEmpty()) return str;
			}
		}
		return "";
	}
	
	public static String cutoffHtml(String val, int len){
		if(null == val || val.length() < len || len < 5) return val;
		int sum = 0, max = len - 3;
		final char[] cs = val.toCharArray();
		final int length = cs.length;
		char c;
		int i = 0, point = 0;
        for (; i < length && sum <= max; ) {  
        	if(((c = cs[i++]) & 0xff00) != 0){
        		sum += 2;
        	}else if(c == ' '){//去掉更多的空格，只允许一个空格
        		while(i < length && cs[i] == ' ') i++;
        		sum ++;  
        	}else if(c == '\n' || c == '\t' || c == '\r'){
        		continue;
        	}else if(c == '<'){//去掉html及格式
        		while(i < length && cs[i++] != '>');
        		continue;
        	}else{
        		sum ++;  
        	}
        	cs[point++] = c;
        }
        cs[point++] = '.';
        cs[point++] = '.';
        cs[point++] = '.';
        return new String(cs, 0, point);
	}
	
	public static String cutoffText(String val, int len){
		if(len == -1){
			if(null == val) return val;
			return val.replace("<", "&lt;").replace(">", "&gt;");
		}
		if(null == val || val.length() < len || len < 5) return val;
		int sum = 0, max = len - 3;
		StringBuilder sb = new StringBuilder(max);
        for (int i = 0; i < val.length() && sum <= max; i++) {  
        	char c = val.charAt(i);
            if((c & 0xff00) != 0) sum += 2;
            else sum += 1;
            sb.append(c);
        }
        return sb.append("...").toString();  
	}
	
	/**
	 * <pre>
	 * 在显示的时候对字段进行保密处理，如，只显示前后1位，中间用*号代替等
	 * 
	 * 比如：
	 *     姓名：陈*中
	 *     手机：138*****453
	 *     身份证：44************4435
	 * 
	 * 其中存在这样的情况，字符串长度为3或4，指定显示前2个和后2个，则显示字段需要4个，
	 * 本来应该是全部显示，但这种情况应该是前后显示1个字符，中间替换为指定的符号，
	 * </pre>
	 * @param source
	 * @param replace
	 * @param first
	 * @param last
	 * @return
	 */
	public static String secrecy(String source, char replace, int first, int last){
		char[] chs = source.toCharArray();
		int len = chs.length;
		if(len < 2){
			return source;
		}else if(len == 2){
			chs[last > first ? 0 : 1] = replace;
		}else{//这里的len值肯定是大于2的数
			int tf = first, tl = last;
			while(len <= (tf + tl)){
				if(tf > 0) tf--;
				if(tl > 0) tl--;
			}
			tl = len - tl;
			for(;tf < tl; tf++){
				chs[tf] = replace;
			}
		}
		return new String(chs);
	}
	
	// 统计字符串中的子串出现次数
	public static int getOccur(String src, String find) {
		int count = 0;
		int index = -1;
		while ((index = src.indexOf(find, index)) > -1) {
			++index;
			++count;
		}
		return count;
	}
	
	// str 中只能包含 c 中的字符
	public static boolean isOnlyContain(String str, char[] c) {
		if (isEmpty(str) || null == c || c.length == 0)
			return true;
		
		boolean flag = false;
		char[] s = str.toCharArray();
		for (char _s : s) {
			flag = false;
			for (char _c : c) {
				if (_s == _c) {
					flag = true;
					break;
				}
			}
			if (!flag) {
				break;
			}
		}
		return flag;
	}

	// str 中不能包含 c 中的字符
	public static boolean isNotContain(String str, char[] c) {
		if (isEmpty(str) || null == c || c.length == 0)
			return true;
		
		boolean flag = false;
		char[] src = str.toCharArray();
		for (char _src : src) {
			flag = false;
			for (char _c : c) {
				if (_src == _c) {
					flag = true;
					break;
				}
			}
			if (flag) {
				break;
			}
		}
		return !flag;
	}

	public static boolean equals(String str0, String str1) {
		return isNotEmpty(str0) && str0.equals(str1);
	}
	//去空格 tab
	public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        dest=remove(dest);
        return dest.replace(" ", "");
	}

	public static String remove(String resource) {
		StringBuffer buffer = new StringBuffer();
		int position = 0;
		char currentChar;
		char ch=' ';

		while (position < resource.length()) {
			currentChar = resource.charAt(position++);
			if (currentChar != ch)
				buffer.append(currentChar);
		}
		return buffer.toString();
	}
	public static String getIdCard(String idCard){
   		if (idCard==null) {
			return idCard;
		}
		String regEx="[^0-9]";   
		Pattern p = Pattern.compile(regEx);   
		Matcher m = p.matcher(idCard);   
		String idCard2=m.replaceAll("").trim();
		if (idCard.contains("x")) {
			idCard2=idCard2+"X";
		}else if (idCard.contains("X")) {
			idCard2=idCard2+"X";
		}
		return idCard2;
		
	}
	/** 
     * 通过对象和具体的字段名字获得字段的值 
     * @param obj 目的对象 
     * @param filed 字段名 
     * @return 通过字段名得到字段值 
     */  
	public static Object getValueByFiled(Object obj, String filed) {
		try {
			Class<?> clazz = obj.getClass();
			PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);
			Method getMethod = pd.getReadMethod();// 获得get方法
			Object o = getMethod.invoke(obj);// 执行get方法返回一个Object
			return o;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
     * 利用正则表达式判断字符串是否是数字
     * @param str
     * @return boolean
     */
    public static boolean isNumeric(String str){
           Pattern pattern = Pattern.compile("[0-9]*");
           Matcher isNum = pattern.matcher(str);
           if( !isNum.matches() ){
               return false;
           }
           return true;
    }
    // 判断一个字符是否是中文  
    public static boolean isChinese(char c) {  
        return c >= 0x4E00 &&  c <= 0x9FA5;// 根据字节码判断  
    }  
    // 判断一个字符串是否含有中文  
    public static boolean isContainsChinese(String str) {  
        if (str == null) return false;  
        for (char c : str.toCharArray()) {  
            if (isChinese(c)) return true;// 有一个中文字符就返回  
        }  
        return false;  
    }  
    
    /**
     * 获取文件后缀名
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {   
        if ((filename != null) && (filename.length() > 0)) {   
            int dot = filename.lastIndexOf('.');   
            if ((dot >-1) && (dot < (filename.length() - 1))) {   
                return filename.substring(dot + 1);   
            }   
        }   
        return filename;   
    }   
    /**
    * 获取文件名
    * @param filename
    * @return
    */
    public static String getFileNameNoEx(String filename) {   
        if ((filename != null) && (filename.length() > 0)) {   
            int dot = filename.lastIndexOf('.');   
            if ((dot >-1) && (dot < (filename.length()))) {   
                return filename.substring(0, dot);   
            }   
        }   
        return filename;   
    }
    
    
    
    /**
     * 判断是否图片格式
     * @param filename 文件名
     * @return boolean
     */
     public static boolean isImage(String filename) {
		String[] suffixs={"jpg","png","jpeg","gif","jpe"};
		String suffix=getExtensionName(filename);
		for (String string : suffixs) {
			if (string.equalsIgnoreCase(suffix)) {
				return true;
			}
		}
		return false;
	}
    
     
     /**
      * 判断是否图片或者pdf文档格式
      * @param filename 文件名
      * @return boolean
      */
      public static boolean isImageOrPdf(String filename) {
    	  String[] suffixs={"jpg","png","jpeg","gif","jpe","pdf"};
		  String suffix=getExtensionName(filename);
		  for (String string : suffixs) {
				if (string.equalsIgnoreCase(suffix)) return true;
		  }
		  return false;
      }
      
      /**
       * 判断身份证是否合法身份证
       * @param filename 文件名
       * @return boolean
       */
       public static boolean isLegalIdCard(String idCard) {
			if (isEmpty(idCard)) {
				return false;
			}else if (idCard.length()<15) {
				return false;
			}
		    return true;
       }
      
       /**
        * 四舍五入保留小数
        * @param total double数字
        * @param lenth 保留位数
        * @return
        */
	   	public static double decimal(Double total,int lenth){
	   		BigDecimal   b   =   new   BigDecimal(null==total?0:total); 
	   		return b.setScale(lenth,  BigDecimal.ROUND_HALF_UP).doubleValue();  
	   	}
}
